<template>
  <div class="app-container">
    <el-container style="border: 1px solid #eee">
      <el-header height="104px">
        <el-row :gutter="20">
          <el-col :span="12">
            <span>数据源:</span>
            <el-select v-model="select_web" placeholder="选择数据源" size="small" filterable clearable @change="handleChangeWeb">
              <el-option label="所有" value="-1" />
              <el-option
                v-for="item in dataWebs"
                :key="item.id"
                :label="item.domain"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="12">
            <span>目录 :</span>
            <el-select
              v-model="select_category"
              v-loading="categoryLoading"
              placeholder="选择目录"
              size="small"
              filterable
              clearable
            >
              <el-option
                v-for="(item,index) in dataCategories"
                :key="index"
                :value="item.category_name"
                :label="'[' + item.product_count + ']' + item.category_name"
              />
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <span>关键词:</span>
            <el-select
              v-model="select_keyword"
              v-loading="keywordLoading"
              placeholder="选择关键词"
              size="small"
              filterable
              clearable
              remote
              :remote-method="remoteGetSearchKeyword"
            >
              <el-option
                v-for="(item,index) in dataKeywords"
                :key="index"
                :value="item.id"
                :label="'[' + item.product_count + '] ' + item.keyword+ ' <' + item.target_web__domain + '>'"
              />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="kwInput"
              placeholder="输入关键词进行搜索"
              style="width: calc(100% - 110px);margin-right: 10px"
              size="small"
              clearable
              @keyup.native.enter="handleSearch"
            >

              <el-button slot="append" type="success" icon="el-icon-search" @click="handleSearch">查询</el-button>
            </el-input>
          </el-col>
        </el-row>
      </el-header>
      <el-main style="border-top: 1px solid rgb(238, 238, 238)">
        <div style="float: left;margin-bottom: 5px">
          <el-select
            v-model="direct_upload_web_id"
            size="mini"
            filterable
            clearable
            placeholder="选择直接上传的网站"
          >
            <el-option
              v-for="item in websites"
              :key="item.id"
              :label="item.domain"
              :value="item.id"
              :disabled="item.type !== 'PrestaShop'"
              @change="handleDirectUPloadChange"
            />
          </el-select>
          <el-button
            v-if="direct_upload_able && direct_upload_web_id"
            size="mini"
            type="primary"
            :disabled="!multipleSelection.length"
            @click.native.stop="handleClickDirectUpload()"
          >上传选择
          </el-button>
          <el-button
            v-if="direct_upload_able && direct_upload_web_id"
            size="mini"
            type="primary"
            @click.native.stop="handleClickDirectUploadAll()"
          >批量上传
          </el-button>

          <el-button
            v-if="direct_upload_able && direct_upload_web_id"
            size="mini"
            :type="direct_upload_state"
            @click.native.stop="handleCHooseDirectuploadCategory()"
          >配置目录
          </el-button>

          <el-select v-model="uploadedonly" size="mini" placeholder="请选择" @change="getList">
            <el-option
              v-for="item in uploadedonlyoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button size="mini" type="info" @click="directlyUploadTaskVisible=true"><i class="el-icon-tickets" /></el-button>
          <el-button v-if="direct_upload_web_id != ''" size="mini" type="primary" @click="getRemoateProduct">编辑产品</el-button>
        </div>
        <div style="float: right;margin-bottom: 5px">
          <el-button size="mini" type="warning" @click="swapImage">替换图片</el-button>
          <el-button
            v-if="select_web != '-1'"
            :loading="editLoading"
            type="danger"
            size="mini"
            :disabled="!multipleSelection.length"
            @click="handleBatchEdit"
          >编辑选中产品
          </el-button>

          <el-dropdown v-if="select_web != '-1'" trigger="click">
            <el-button
              type="primary"
              size="mini"
              :loading="uploadLoading"
              :disabled="!multipleSelection.length"
              style="margin-right: 20px;margin-bottom: 10px;"
            >
              模板上传<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in websites"
                :key="item.id"
                :disabled="item.type !== 'PrestaShop'"
                @click.native.stop="handleClickTemplateUpload(item)"
              >{{ item.domain }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button size="mini" title="进入批量编辑页面" type="danger" @click="location2export('edit')">批量编辑
          </el-button>
          <el-button size="mini" title="进入批量上传页面" type="success" @click="location2export('upload')">批量上传
          </el-button>
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          :default-sort="{prop: 'name', order: 'descending'}"
          style="width: 100%"
          @sort-change="handleSort"
          @selection-change="handleSelectionChange"
        >

          <el-table-column
            type="selection"
            width="55"
          />

          <el-table-column align="center" width="80" prop="id" label="id" />

          <el-table-column
            align="center"
            fixed
            label="图片"
            width="300"
          >
            <template slot-scope="scope">
              <el-row>
                <el-col :span="12">
                  <el-tooltip class="item" effect="light" placement="right">
                    <div slot="content"><img :src="scope.row.image" width="320"></div>
                    <img :src="scope.row.image" width="90" @click="handleViewCrawlProductImage(scope.row)">
                  </el-tooltip>
                </el-col>
                <el-col :span="12">
                  <div><a
                    :href="'https://www.google.com/searchbyimage?site=search&sa=X&image_url='+scope.row.image"
                    target="_blank"
                  >Google</a></div>
                  <div><a :href="scope.row.url" target="_blank">原链接</a></div>
                  <div>
                    <el-button type="text" size="small" @click="handleSearchImage(scope.row)">搜索</el-button>
                    <el-button v-if="sync_able" type="text" size="small" @click="handleSearchReview(scope.row)">review</el-button>
                  </div>
                </el-col>
              </el-row>

            </template>
          </el-table-column>

          <!--<el-table-column-->
          <!--align="center"-->
          <!--prop="category_name"-->
          <!--label="category"-->
          <!--width="150">-->
          <!--</el-table-column>-->
          <!--<el-table-column-->
          <!--align="center"-->
          <!--prop="product_type"-->
          <!--label="产品类别"-->
          <!--sortable="custom"-->
          <!--width="120">-->
          <!--</el-table-column>-->
          <el-table-column
            align="center"
            label="name"
          >
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="meta信息"
                width="600"
                trigger="hover"
              >
                <div>[name]{{ scope.row.name }}</div>
                <hr>
                <div>[meta_title]{{ scope.row.meta_title }}</div>
                <hr>
                <div>[meat_desc]{{ scope.row.meta_description }}</div>
                <hr>
                <div>[url]{{ scope.row.url }}</div>

                <span slot="reference">{{ scope.row.name }}
                  <br>
                  <el-tag v-if="scope.row.search_keyword" type="success">{{ scope.row.search_keyword }}</el-tag>
                  <el-tag v-if="scope.row.category_name" type="danger">{{ scope.row.category_name }}</el-tag>
                  <el-tag type="danger">{{ scope.row.price }}</el-tag>
                </span>

              </el-popover>

            </template>
          </el-table-column>
          <el-table-column align="center" width="300" prop="upload_count" label="上传次数" />
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="120"
          >
            <template slot-scope="scope">
              <el-dropdown
                split-button
                style="float: right"
                type="danger"

                @click="handleModify(scope.row)"
              >
                {{ '编辑' }}
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="sync_able" @click.native.stop="handleSync(scope.row)">同步</el-dropdown-item>
                  <el-dropdown-item @click.native.stop="handleDelete(scope.row)">删除产品</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.upload_count > 0" @click.native.stop="handleDeleteUploadTask(scope.row)">删除上传记录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="tableData.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,50,100,200,300,500]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <el-dialog :visible.sync="imageReplacerVisible" title="爬取产品图片替换" @close="hide">
      <span>注意：要求严格的图片命名 id.png id将被作用于 产品id对应项</span>
      <el-upload
        ref="upload"
        :headers="headers"
        :action="base_api"
        :on-success="handleUploadSuccess"
        :file-list="fileList"
        multiple
        accept=".jpg,.png,.jpeg,.gif"
        list-type="picture"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </el-upload>

    </el-dialog>

    <el-dialog
      v-loading.fullscreen.lock="categoryDialogLoading"
      :visible.sync="categoryDialogVisible"
      :title="categoryDialogTitle"
      class="category-select"
      @close="hideSelectCategory"
    >
      <el-input v-model="filterText" placeholder="输入关键字进行过滤" size="mini" clearable />
      <el-tree
        ref="categoryTree"
        :data="catalogs"
        node-key="id"
        :default-expanded-keys="catalogs.length?[catalogs[0].id]:[]"
        :filter-node-method="filterCategoryNode"
        check-strictly
        :expand-on-click-node="false"
        :props="{ children: 'children', label: 'name' }"
        @node-click="handleSelectTargetCategory"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>{{ data.id + ' | ' + node.label }}</span>
          <span><el-button
            v-if="data.children.length"
            type="text"
            size="mini"
            style="margin-right: 20px"
            @click="showAddCategoryDialog(data)"
          >添加</el-button></span>
        </span>
      </el-tree>
      <el-button
        plain
        icon="el-icon-refresh"
        title="刷新"
        size="mini"
        @click="handleFetchWebsiteCatalogs"
      />
      <p>选中目录: {{ target_category_name }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="categoryDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="!target_category_name"
          @click="handleSelectWebsiteUpload"
        >确 定</el-button>
      </span>

      <el-dialog
        v-loading.fullscreen.lock="addCategoryLoading"
        title="添加目录"
        :visible.sync="addCategoryDialogVisible"
        width="80%"
        append-to-body
        class="mt-add-category-dialog"
      >
        <el-form :model="addCategory" label-position="left" label-width="140px">
          <el-form-item label="* Name">
            <el-input v-model="addCategory.name" />
          </el-form-item>

          <el-form-item label="Displayed">
            <el-switch
              v-model="addCategory.active"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0"
              inactive-color="#ff4949"
            />
          </el-form-item>

          <br>
          <el-form-item label="描述">
            <tinymce ref="mtdescription" v-model="addCategory.description" :height="300" />
          </el-form-item>
          <el-form-item label="Meta title">
            <el-input v-model="addCategory.meta_title" />
          </el-form-item>

          <el-form-item label="Meta description">
            <el-input v-model="addCategory.meta_description" />
          </el-form-item>

          <el-form-item label="Meta keywords">
            <el-input v-model="addCategory.meta_keywords" />
          </el-form-item>

          <el-form-item label="* Friendly URL">
            <el-input v-model="addCategory.friendly_url" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddCategory">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>

    <review
      :target_id="target_id"
      :product_url="review_target_url"
      :title="review_title"
      :review_visuable="review_visualbe"
      @closeDialog="review_visualbe=false"
    />
    <crawlimage
      :product_id="target_id"
      :titlename="crawlimage_dialog_title"
      :image-dialog-visible="crawlimage_visualbe"
      @closeDialog="crawlimage_visualbe=false"
    />
    <choosecategory
      :website_id="direct_upload_web_id"
      :choosedialog-visible="direct_upload_dialogVisible"
      :default_catalog="direct_upload_default_category"
      :default-checked-keys="direct_upload_associated_categories"
      @SetChoose="handleSetDirectUploadCategories"
      @closeDialog="direct_upload_dialogVisible=false"
    />
    <directlyuploadtask
      :task-visible="directlyUploadTaskVisible"
      @closeCrawlTaskDialog="directlyUploadTaskVisible=false"
    />
    <prestaproduct
      :domain="currentOpRow.web__domain"
      :local_id="currentOpRow.id"
      :product_id="currentOpRow.product_id"
      :pst-visible="remoteModifydialogVisible"
      @closePstDialog="remoteModifydialogVisible=false"
    />
  </div>
</template>

<script>
import {
  GetWebs,
  GetWebItems,
  template_add_item_to_task,
  direct_add_item_to_task,
  GetWebCategory,
  crawl_modify_remote,
  SyncProductInfo,
  crawl_product_batch_edit,
  DeleteWebItems,
  DeleteUploadTask
} from '@/api/erp/crawlproduct'
import { Get as GetWebKeyword } from '@/api/erp/crawl/searchkey'
import { CatalogTree as GetWebsiteCatalogs, Get as GetWebsite, AddCategory } from '@/api/erp/elicink/website'
import { getToken } from '@/utils/auth'
import { SearchSimilarFromBaidu } from '@/api/erp/crawlproduct'
import qs from 'qs'
import crawlimage from '@/views/crawl/elements/crawlimage'
import directlyuploadtask from '@/views/crawl/elements/directlyuploadtask'
import review from '@/views/review/elements/review'
import Tinymce from '@/components/Tinymce'
import Choosecategory from '../prestashop/element/choosecategory'
import prestaproduct from '@/views/prestashop/element/prestaproduct'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  components: { Choosecategory, Tinymce, review, crawlimage, directlyuploadtask, prestaproduct },
  data() {
    return {
      directlyUploadTaskVisible: false,
      dataWebs: [],
      ChoosecategoryDialogVisible: false,
      target_id: -1,
      review_target_url: '',
      review_visualbe: false,
      crawlimage_visualbe: false,
      crawlimage_dialog_title: '图片管理',
      review_title: 'review管理',
      tableData: [],
      select_web: -1,
      select_category: null,
      dataCategories: [],
      select_keyword: null,
      keywordLoading: false,
      dataKeywords: [],
      loading: false,
      loading2: false,
      direct_upload_able: false,
      direct_upload_state: 'warning',
      direct_upload_web_id: '',
      direct_upload_dialogVisible: false,
      direct_upload_associated_categories: [],
      direct_upload_default_category: 2,
      newtoall: false,
      // pagination
      kwInput: '',
      pagesize: 10,
      page: 1,
      total: 0,
      order_by: '',
      order_desc: '',
      sync_able: false, // 是否可以同步
      websites: [],
      categoryLoading: false,
      editLoading: false,
      uploadLoading: false,
      imageReplacerVisible: false,
      fileList: [],
      history: [],

      categoryDialogVisible: false,
      categoryDialogLoading: false,
      filterText: '',
      categoryDialogTitle: '',
      catalogs: [],

      addCategoryDialogVisible: false,
      addCategoryLoading: false,
      addCategory: {
        name: '',
        active: '1',
        id_parent: null,
        description: '',
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        friendly_url: ''
      },
      target_category_name: '',
      remoteModifydialogVisible: false,
      searchResults: [],
      searchImageUrl: '',
      currentOpRow: {
        'id': 0,
        'name': '',
        'price': '',
        'description': '',
        'long_description': '',
        'meta_title': '',
        'meta_description': '',
        'meta_keywords': '',
        'web__domain': '',
        'product_id': ''
      },
      uploadedonly: 'all',
      uploadedonlyoptions: [
        {
          value: 'all',
          label: '所有'
        },
        {
          value: 'uploaded',
          label: '已经上传'
        },
        {
          value: 'unupload',
          label: '目标网站未上传'
        },
        {
          value: 'newtoall',
          label: '所有网站未上传'
        }
      ],
      // currentOpMainInfo: { 'name': '', 'price': '', 'description': '', 'long_description': '' },
      // currentOpMetaInfo: { 'meta_title': '', 'meta_description': '', 'meta_keywords': '' },
      activeName: 'first',
      currentIndex: -1,
      multipleSelection: []
    }
  },
  computed: {
    // 目录名称
    k: function() {
      return this.$route.query.k
    },
    // 搜索关键词
    sk: function() {
      return this.$route.query.sk
    },
    skid: function() {
      return this.$route.query.skid
    },
    // 数据源
    w: function() {
      return this.$route.query.w
    },
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  created() {
    GetWebs().then((response) => {
      this.dataWebs = response.data
    }).catch(error => {
      console.log(error)
    })

    GetWebsite().then(response => {
      this.websites = response.data.data
    })
    if (this.w) {
      this.fetchCategories()
    }
    if (this.sk) {
      this.keywordLoading = true
      GetWebKeyword(null, `web_id=${this.w}&kw=${this.sk}`).then(response => {
        this.dataKeywords = response.data.data
        this.select_keyword = this.dataKeywords[0].id
        this.keywordLoading = false
      }).catch(e => {
        this.keywordLoading = false
      })
    }
    this.select_category = this.k || null
    this.select_web = this.w && parseInt(this.w) || '-1'
    if (this.select_web) {
      this.direct_upload_able = true
    }
    // this.$nextTick(() => {
    // })
    // if (this.w) {
    //   this.getList();
    // }

    this.base_api = process.env.VUE_APP_BASE_API + '/erp/api/crawl_product/'
  },
  methods: {
    // pageSize 改变后触发 table 更新
    getList() {
      this.loading = true
      GetWebItems(qs.stringify({
        web: this.select_web,
        category: this.select_category,
        crawl_keyword: this.select_keyword,
        kw: this.kwInput,
        order_by: this.order_by,
        order_desc: this.order_desc,
        pagesize: this.pagesize,
        newtoall: this.newtoall,
        uploadedonly: this.uploadedonly,
        upload_web_id: this.direct_upload_web_id,
        page: this.page
      }))
        .then(response => {
          this.tableData = response.data.data
          this.loading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    getRemoateProduct() {
      if (this.direct_upload_web_id) {
        var i = 0
        for (i = 0; i < this.websites.length; i++) {
          if (this.websites[i].id === this.direct_upload_web_id) {
            this.currentOpRow.id = ''
            this.currentOpRow.product_id = ''
            this.remoteModifydialogVisible = true
            this.currentOpRow.web__domain = this.websites[i].domain
            // console.log(this.currentOpRow)
          }
        }
      }
    },
    remoteGetSearchKeyword(query) {
      if (query !== '' && query[query.length - 1] === '#') {
        this.keywordLoading = true
        GetWebKeyword(null, `web_id=${this.select_web}&kw=${query}`).then(response => {
          this.dataKeywords = response.data.data
          this.keywordLoading = false
        }).catch(e => {
          this.keywordLoading = false
        })
      }
    },
    handleUpload() {
      this.page = 1
      this.getList()
    },
    handleSync(row) {
      SyncProductInfo(row.id).then((response) => {
        this.$notify({
          title: '成功',
          message: '产品信息同步成功,页面会自动刷新',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    handleDelete(row) {
      if (!confirm('确定要删除吗？')) {
        return
      }
      DeleteWebItems(row.id).then((response) => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    handleDeleteUploadTask(row) {
      DeleteUploadTask(row.id).then((response) => {
        this.$notify({
          title: '成功',
          message: '删除上传记录成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    handleModify(row) {
      if (this.currentOpRow.id !== row.id) {
        this.currentIndex = -1
      }

      this.activeName = 'first'
      this.currentOpRow = row
      // this.currentOpMainInfo.id = row.id
      // this.currentOpMainInfo.name = row.name
      // this.currentOpMainInfo.price = row.price
      // this.currentOpMainInfo.description = row.description
      // this.currentOpMainInfo.long_description = row.long_description
      // this.currentOpMetaInfo.meta_title = row.meta_title
      // this.currentOpMetaInfo.meta_desc = row.meta_desc
      // this.currentOpMetaInfo.meta_keywords = row.meta_keywords
      // this.currentOpMetaInfo.isDisable = row.isDisable
      // if (this.currentOpRow.description != null) {
      //   this.$nextTick(() => {
      //     if (this.$refs.hasOwnProperty('mteditdescription')) {
      //
      //       this.$refs.mteditdescription.setContent(this.currentOpRow.description)
      //     }
      //   }
      //   )
      // } else {
      //   this.$nextTick(() => {
      //     if (this.$refs.hasOwnProperty('mteditdescription')) {
      //       this.$refs.mteditdescription.setContent('')
      //     }
      //   }
      //   )
      // }
      this.remoteModifydialogVisible = true
      this.searchImageUrl = row.image
      // this.currentOpRow.isDisable = false;
      if (this.currentOpRow.description != null) {
        this.$nextTick(() => {
          if (this.$refs.mteditdescription.hasInit && this.currentOpRow.description != null) {
            this.$refs.mteditdescription.setContent(this.currentOpRow.description != null ? this.currentOpRow.description : '')
          }
          if (this.$refs.mteditdlongdescription.hasInit) {
            this.$refs.mteditdlongdescription.setContent(this.currentOpRow.long_description != null ? this.currentOpRow.long_description : '')
          }
        }
        )
      }
    },

    handleSaveModifyRemote(isRemote) {
      // var d = Object.assign(this.currentOpMainInfo, this.currentOpMetaInfo)
      this.loading = true
      crawl_modify_remote(JSON.stringify({
        data: this.currentOpRow,
        isRemote: isRemote
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: response.message,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        }).catch(err => {
          this.$notify({
            title: '失败',
            message: err,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        })
    },
    OnNextItem() {
      this.currentIndex = this.currentIndex + 1
      if (this.searchResults.length <= this.currentIndex) {
        this.currentIndex -= 1
        console.log(this.searchResults.length)
      }
      console.log(this.currentIndex)
    },
    handleModifyTabClick() {
      if (this.activeName === 'second') {
        this.loading2 = true
        SearchSimilarFromBaidu(JSON.stringify({ imgurl: this.currentOpRow.image })).then((response) => {
          this.loading2 = false
          this.searchResults = response.data
          this.currentIndex = 0
        }).catch(error => {
          console.log(error)
          this.loading2 = false
        })
      }
    },
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    handleSearchImage(row) {
      // this.$router.push({ name: 'cralwweb', query: { targetimg: row.image }})
      const link = this.$router.resolve({ name: 'cralwweb', query: { targetimg: row.image }})
      window.open(link.href, '_blank')
    },
    handleSearchReview(row) {
      this.target_id = row.id
      this.review_target_url = row.url
      this.review_visualbe = true
      this.review_title = row.name + '-reviews'
    },
    handleViewCrawlProductImage(row) {
      this.target_id = row.id
      this.crawlimage_dialog_title = row.name + '-图片管理'
      this.crawlimage_visualbe = true
      console.log(this.crawlimage_dialog_title)
    },
    // 点击替换图片
    swapImage() {
      this.imageReplacerVisible = true
    },
    handleUploadSuccess(res) {
      // 如果上传成功 记录历史，用于 刷新 父控件
      if (res.success) {
        this.history.push(1)
        this.notify(res.data.name + '上传成功')
      } else {
        this.$notify({
          title: '失败',
          message: res.msg,
          type: 'error',
          duration: 8000
        })
      }
    },
    hide() {
      if (this.history.length) {
        this.getList()
        this.history = []
        this.fileList = []
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    location2export(choice) {
      let query
      switch (choice) {
        case 'edit': {
          query = { process_type: '2' }
          break
        }
        case 'upload': {
          query = { process_type: '1' }
          break
        }
      }
      const link = this.$router.resolve({
        name: 'erp.productExport2',
        params: { src: 'crawl' },
        query: query
      })
      window.open(link.href, '_blank')
    },
    handleChangeWeb(v) {
      if (v) {
        this.sync_able = false
        this.select_category = null
        this.fetchCategories()
        this.fetchKeywords()
        var x
        this.direct_upload_able = false
        for (x in this.dataWebs) {
          if (this.dataWebs[x].id === v) {
            if (this.dataWebs[x].private) {
              this.sync_able = true
            }
            if (this.dataWebs[x].type === 'aliexpress') {
              this.direct_upload_able = true
            }
            break
          }
        }
      }
    },
    fetchCategories() {
      this.categoryLoading = true
      GetWebCategory(null, `only_name=1&web=${this.select_web}`).then(response => {
        this.dataCategories = response.data
        this.categoryLoading = false
      }).catch(e => {
        this.categoryLoading = false
      })
    },
    fetchKeywords() {
      this.keywordLoading = true
      GetWebKeyword(null, `web_id=${this.select_web}&kw=${this.sk}`).then(response => {
        this.dataKeywords = response.data.data
        this.keywordLoading = false
      }).catch(e => {
        this.keywordLoading = false
      })
    },
    handleFetchWebsiteCatalogs() {
      this.categoryDialogLoading = true
      GetWebsiteCatalogs(this.uploadTargetWebsite.id).then(respone => {
        this.catalogs = respone.data
        this.categoryDialogLoading = false
      }).catch(e => {
        this.categoryDialogLoading = false
      })
    },
    handleShowUploadCategoryDialog(v) {
      //   this.categoryDialogVisible = true
      //   this.categoryDialogTitle = v.domain + ' 指定上传目录'
      //   this.uploadTargetWebsite = v
      //   this.addCategory = {
      //     name: '',
      //     active: '1',
      //     id_parent: null,
      //     description: '',
      //     meta_title: '',
      //     meta_description: '',
      //     meta_keywords: '',
      //     friendly_url: ''
      //   }
      //   this.target_category_name = ''
      //   if (this.uploadTargetWebsite.type === 'PrestaShop') {
      //     this.handleFetchWebsiteCatalogs()
      //   }
    },
    handleClickTemplateUpload(v) {
      this.loading = true
      template_add_item_to_task(JSON.stringify({
        pks: this.multipleSelection,
        target_web_id: v.id
      })).then(resonse => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: resonse.message,
          type: 'success',
          duration: 4500
        })
      }).catch(e => {
        this.loading = false
      })
    },
    handleClickDirectUpload(v) {
      this.loading = true
      direct_add_item_to_task(JSON.stringify({
        pks: this.multipleSelection,
        newtoall: this.newtoall,
        associated_categories: this.direct_upload_associated_categories,
        default_category: this.direct_upload_default_category,
        target_web_id: this.direct_upload_web_id
      })).then(resonse => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: resonse.message,
          type: 'success',
          duration: 4500
        })
      }).catch(e => {
        this.loading = false
      })
    },
    handleCHooseDirectuploadCategory() {
      this.direct_upload_dialogVisible = true
    },
    handleSetDirectUploadCategories(v) {
      this.direct_upload_default_category = v.default_catalog
      this.direct_upload_associated_categories = v.target_catalogs
      if (this.direct_upload_associated_categories.indexOf(2) === -1) {
        this.direct_upload_state = 'warning'
      } else {
        this.direct_upload_state = 'success'
      }
    },
    handleClickDirectUploadAll() {
      this.$prompt('请输入(1-5000)的数值', '批量上传的产品数量', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputErrorMessage: '请输入数字'
      }).then(({ value }) => {
        this.loading = true
        direct_add_item_to_task(JSON.stringify({
          pks: [],
          newtoall: this.newtoall,
          max_count: value,
          web: this.select_web,
          associated_categories: this.direct_upload_associated_categories,
          default_category: this.direct_upload_default_category,
          crawl_keyword: this.select_keyword,
          target_web_id: this.direct_upload_web_id
        })).then(resonse => {
          this.loading = false
          this.$notify({
            title: '成功',
            message: resonse.message,
            type: 'success',
            duration: 4500
          })
        }).catch(e => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleDirectUPloadChange() {
      this.getList()
    },
    hideSelectCategory() {
      this.categoryDialogVisible = false
    },
    showAddCategoryDialog(data) {
      this.addCategory = {
        name: '',
        active: '1',
        id_parent: data.id,
        description: '',
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        friendly_url: ''
      }
      this.$nextTick(() => {
        this.$refs.mtdescription.destroyTinymce()
        this.$refs.mtdescription.initTinymce()
        this.$refs.mtdescription.setContent('')
      })
      this.addCategoryDialogVisible = true
    },
    handleAddCategory() {
      this.addCategoryLoading = true
      AddCategory(Object.assign(this.addCategory, { website_id: this.uploadTargetWebsite.id }))
        .then(response => {
          this.addCategoryLoading = false
          this.addCategoryDialogVisible = false
          this.handleFetchWebsiteCatalogs()
        })
        .catch(e => {
          this.addCategoryLoading = false
        })
    },
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) !== -1
    },
    handleSelectTargetCategory(v) {
      this.target_category_name = v.name
    },
    // 选择批量编辑
    handleBatchEdit() {
      this.editLoading = true
      console.log(this.multipleSelection)
      // 获取选择的产品
      if (this.multipleSelection.length === 0) {
        alert('请先选择产品')
        return
      }
      crawl_product_batch_edit(JSON.stringify({
        product_ids: this.multipleSelection
      })).then(response => {
        this.editLoading = false
        this.$notify({
          title: '成功',
          message: '产品已经添加到批量处理列表',
          type: 'success',
          duration: 1500
        })
      }).catch(e => {
        this.editLoading = false
      })
    },
    // 选择站点上传
    handleSelectWebsiteUpload() {
      //   this.uploadLoading = true
      //   add_crawl_product_to_task(JSON.stringify({
      //     kw: this.kw,
      //     select_web: this.select_web,
      //     website_id: this.uploadTargetWebsite.id,
      //     category_name: this.select_category,
      //     target_category_name: this.target_category_name
      //   })).then(response => {
      //     this.uploadLoading = false
      //     this.$notify({
      //       title: '成功',
      //       message: '本次任务将进入队列中，筛选完成将在通知栏显示',
      //       type: 'success',
      //       duration: 1500
      //     })
      //     this.categoryDialogVisible = false
      //   }).catch(e => {
      //     this.uploadLoading = false
      //   })
    },
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.multipleSelection = val.map(m => m.id)
      }
    }
    // method end
  }
}
</script>

<style scoped>
  .el-row {
    margin-bottom: 20px;

  &
  :last-child {
    margin-bottom: 0;
  }

  }

  .el-col {
    border-radius: 4px;
  }

  .app-container >>> .el-select .el-input {
    width: 330px;
  }

  .app-container >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .app-container >>> .text {
    font-size: 14px;
  }

  .app-container >>> .el-cascader {
    width: 30%;
  }

  .category-select >>> .mt-supplier-code-input {
    width: 80%;
  }

  .category-select >>> .el-dialog {
    margin-top: 40px !important;
    margin-bottom: 20px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .mt-edit-product-dialog >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 48px;
  }
</style>
